# coding=utf-8

import re
from collections import namedtuple
from mobi_lib import BuildNCX, BuildTOC

PATTERN1 = """<li>\n<p><a href="([^"]+)">([^<]+)</a></p>\n(<ul>\n((<li><a href="([^"]+)">([^<]+)</a></li>\n)+)</ul>\n)?</li>"""
PATTERN2 = """<li><a href="([^"]+)">([^<]+)</a></li>\n"""
with open("LearnVimscriptTheHardWay.html", encoding="utf-8") as f:
    s = f.read()

t = namedtuple('FileItem', 'text href id sf')
st = namedtuple('SubFileItem', 'text anchor id')

def Data(filename):
    with open(filename, encoding="utf-8") as f:
        s = f.read()
    id = 0
    it1 = re.finditer(PATTERN1, s)
    rs = []
    for p1 in it1:
        print(p1.group(1), p1.group(2))
        ss = []
        if p1.group(3):
            it2 = re.finditer(PATTERN2, p1.group(3))
            for p2 in it2:
                print("*" * 5, p2.group(1), p2.group(2))
                # id += 1
                ss.append(st(p2.group(2), p2.group(1), str(id)))
        id += 1
        rs.append(t(str(id) + " " + p1.group(2), p1.group(1), str(id), ss))
    return rs

if __name__ == "__main__":
    data = Data("LearnVimscriptTheHardWay.html")
    print(data)
    print(BuildTOC(data))
    with open("index.html", "w") as f:
        f.write(BuildTOC(data))
    print(BuildNCX(data))
    with open("LearnVimscriptTheHardWay.ncx", "w") as f:
        f.write(BuildNCX(data))
